package com.standard.logcat

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.standard.logcat.adapter.LogcatAdapter
import com.standard.logcat.entity.LogcatItem
import com.standard.logcat.logBus.LogBus
import com.standard.logcat.logBus.RXObj
import java.util.*

class FloatingWindowImpl(private val context: Context) : FloatingWindow(context) {

    private var adapter: LogcatAdapter? = null

    /**
     * 设置标题，显示当前的activity
     */
    private fun setTitle(title: String) {
        binding.tvTitle.text = title
    }

    /**
     * 初始化事件监听
     */
    override fun initListener() {
        binding.openLogcat.setOnClickListener {
            it.visibility = View.GONE
            binding.llLogcat.visibility = View.VISIBLE
        }
        binding.ivCloseLogcat.setOnClickListener {
            hideLog()
        }

        binding.clearLogcat.setOnClickListener {
            adapter?.setList(LinkedList<LogcatItem>())
        }

        LogBus.log.sub(object : RXObj.Observer<LogcatItem> {
            override fun observe(data: LogcatItem) = refresh(data)
        })

        LogBus.title.sub(object : RXObj.Observer<String> {
            override fun observe(data: String) = setTitle(data)
        })

        LogBus.hideLog.sub(object : RXObj.Observer<Boolean> {
            override fun observe(data: Boolean) = hideLog()
        })
    }

    /**
     * 初始化View
     */
    override fun initView() {
        adapter = LogcatAdapter(data = LinkedList<LogcatItem>())
        binding.rcLogcat.layoutManager = LinearLayoutManager(context)
        binding.rcLogcat.adapter = adapter
    }

    /**
     * 刷新数据
     */
    private fun refresh(log: LogcatItem) {
        adapter?.let {
            if (it.data.size > 100) {
                it.data.removeAt(0)
            }
            it.addData(log)
            binding.rcLogcat.smoothScrollToPosition(it.data.size)
        }

    }

    /**
     * 隐藏log框
     */
    private fun hideLog() {
        binding.llLogcat.visibility = View.GONE
        binding.openLogcat.visibility = View.VISIBLE
    }
}